package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOFileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.user.dtos.WmMaterialDto;
import com.heima.utils.common.SnowflakeIdWorker;
import com.heima.wemedia.context.BaseContext;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.pojos.WmMaterial;
import com.heima.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author 郭文杰
 * @description 针对表【wm_material(自媒体图文素材信息表)】的数据库操作Service实现
 * @createDate 2023-12-04 10:08:42
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>
        implements WmMaterialService {

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private MinIOFileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public void addMaterial(MultipartFile multipartFile) {
        try {
            //判断是否为null
            if (multipartFile == null) {
                throw new CustomException(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
            }

            //上传文件到minio中
            //用户id
            Long userId = BaseContext.getCurrentId();
            //文件路径

            //原文件名称
            String filename = multipartFile.getOriginalFilename();
            //文件后缀
            String lastPrefix = filename.substring(filename.lastIndexOf("."));
            SnowflakeIdWorker idWorker = new SnowflakeIdWorker(10, 10);
            filename = idWorker.nextId() + lastPrefix + "";
            String filePath = fileStorageService.uploadImgFile("", filename, multipartFile.getInputStream());

            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(userId);
            wmMaterial.setUrl(filePath);
            wmMaterial.setType(0);
            wmMaterial.setIsCollection(0);
            wmMaterial.setCreatedTime(new Date());

            //保存数据
            wmMaterialMapper.insert(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Page<WmMaterial> materialList(WmMaterialDto wmMaterialDto) {
        //判断是否为null
        if (wmMaterialDto == null) {
            wmMaterialDto = new WmMaterialDto();
        }

        //校验分页查询条件
        wmMaterialDto.checkParam();

        Page<WmMaterial> page = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        //如果为未收藏设置为null,查询全部
        if (wmMaterialDto.getIsCollection() != 1) {
            wmMaterialDto.setIsCollection(null);
        }

        //查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(
                wmMaterialDto.getIsCollection() != null
                , WmMaterial::getIsCollection
                , wmMaterialDto.getIsCollection());
        queryWrapper
                .eq(WmMaterial::getUserId, BaseContext.getCurrentId())
                .orderByDesc(WmMaterial::getCreatedTime);

        this.page(page, queryWrapper);

        return page;
    }

    /**
     * 图片删除
     *
     * @param id 图片id
     */
    @Override
    public void deletePicture(Integer id) {
        //校验参数
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断图片是否存在
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if (wmMaterial == null) {
            //不存在抛出异常
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //存在,判断自媒体文章是否引用当前图片素材
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<WmNewsMaterial>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(wrapper);
        if (wmNewsMaterials.size() != 0) {
            throw new CustomException(AppHttpCodeEnum.PICTURE_DELETE_ERROR);
        }

        //删除成功
        wmMaterialMapper.deleteById(id);
    }


}




